package al.xc.redis;

import al.xc.common.util.SingleUtils;

import java.util.Collections;

/**
 * redis分布式锁
 */
public class RedisLock {

    private IRedisConnect connect;

    public RedisLock(IRedisConnect connect) {
        this.connect = connect;
    }

    private static final Long UNLOCK_SUCCESS = 1L;
    private static final String LOCK_SUCCESS = "OK";
    private static final String UNLOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    private static final String LOCK_SCRIPT = "return redis.call('set', KEYS[1], ARGV[1], 'nx', 'ex', '%d')";

    /**
     * 加锁
     * @param lockKey
     * @param identif
     * @param seconds
     * @return
     */
    public boolean trylock(String lockKey, String identif, Integer seconds) {
        Object result = connect.eval(String.format(LOCK_SCRIPT, seconds),
                Collections.singletonList(lockKey), Collections.singletonList(identif));
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }

    /**
     * 释放锁
     * @param lockKey
     * @param identif
     * @return
     */
    public boolean unlock(String lockKey, String identif) {
        Object result = connect.eval(UNLOCK_SCRIPT,
                Collections.singletonList(lockKey), Collections.singletonList(identif));
        if (UNLOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
}
